import React, { Component } from "react";
interface IProps {}

interface IState {
  current: number;
}

export default class CountDown extends Component<IProps, IState> {
  timer: number | null = null;

  state = {
    current: 10, // 秒数
  };

  start = () => {
    this.timer = setInterval(() => {
      this.setState(
        (prevState) => ({
          current: prevState.current - 1,
        }),
        () => {
          if (this.state.current === 0) {
            clearInterval(this.timer as number);
          }
        }
      );

      // // Bug: 到了 -1 才停止。
      // if (this.state.current === 0) {
      //   clearInterval(this.timer as number);
      // }
    }, 1000);
  };

  stop = () => {
    // clearInterval(this.timer as number);
    this.timer && clearInterval(this.timer);
  };

  render() {
    return (
      <div>
        <button>{this.state.current} / 秒</button>
      </div>
    );
  }
}
